package com.jia.train.gateway.filter;

import com.jia.train.gateway.utils.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class LoginMemberFilter implements GlobalFilter {

    public static final Logger logger = LoggerFactory.getLogger(LoginMemberFilter.class);


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        // 登录跳过
        if (antPathMatcher.match("/**/login", path) ||
                antPathMatcher.match("/**/send", path) ||
                antPathMatcher.match("/**/index", path)) {
            logger.info("不需要登录验证：{}", path);
            return chain.filter(exchange);
        }
        // Header 获取
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String bearerToken = headers.getFirst("Authorization");
        logger.info("会员登录验证开始，Authorization token: {}", bearerToken);

        if (bearerToken == null || !bearerToken.startsWith("Bearer ")) {
            logger.info("Authorization token为空，请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // 校验Token
        boolean validate = JwtTokenUtil.validateToken(bearerToken);

        if (validate) {
            logger.info("token 校验通过");
            return chain.filter(exchange);
        } else {
            logger.info("token无效");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }

}
